<?php
namespace Core\CoreComponents\EventsManager;
use Core;

require_once(COMPONENTS_DIR . 'EventsManager/IEvents.php');
require_once(CONTRACTS_DIR . 'event.entity.php');
require_once(CONTRACTS_DIR . 'user.entity.php');
require_once(CONTRACTS_DIR . 'eventsubscription.entity.php');
require_once(CONTRACTS_DIR . 'eventattachment.entity.php');

/**
* This interface provide all accessible methods on event module
*
* @method ServiceResponse addEvent($title, $description, $eventDate, $numberOfPlace)
* @method ServiceResponse attachPosterOnAnEvent($idEvent, $file, $mime, $extension)
* @method ServiceResponse preSubscribe($userId, $eventId)
* @method ServiceResponse getEventSubscriptions()
* @method ServiceResponse getValidEventSubscriptionsForPlannedEvent()
* @method ServiceResponse getEventSubscriptionsToValid()
* @method ServiceResponse updateEventSubscription($id, $state)
* @method ServiceResponse getEvents()
* @method ServiceResponse getStates()
* @method ServiceResponse getEventSubscriptionStates()
* @method ServiceResponse getOnlineEvents()
* @method ServiceResponse getDoneEvents()
* @method ServiceResponse deleteEvent($id)
* @method ServiceResponse updateEvent($id, $title, $description, $startDate, $startTime, $endDate, $endTime, $numberOfPlaces, $archiveName, $state, $location)
* @method ServiceResponse attachArchive($idEvent, $archiveName)
* @method ServiceResponse planEvent($id)
* @method ServiceResponse closeSubscriptionsEvent($id)
* @method ServiceResponse runEvent($id)
* @method ServiceResponse cancelEvent($id)
* @method ServiceResponse doneEvent($id)
* @method ServiceResponse attachEventAttachment($eventId, $file, $mime, $extension)
* @method ServiceResponse getEventAttachments($eventId)
*/
class Events implements IEvents
{
	/**
	* Add a event
	*
	* @param string $title The event title
	* @param string $description The event description
	* @param datetime $startDate The start event date
	* @param datetime $endDate The end event date
	* @param int $numberOfPlace The number of places
	* @param string $location The event location
	* 
	* @return ServiceResponse This response contains the added event
	*/
	public function addEvent($title, $description, $startDate, $startTime, $endDate, $endTime, $numberOfPlaces, $location, $isSubscriptionValidationRequired)
	{
		Core\CoreCommons\Logger::Info("addEvent $title, $description, $startDate, $startTime, $endDate, $endTime, $numberOfPlaces, $location, $isSubscriptionValidationRequired");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$event = Core\CoreContracts\Event::Create($title, $description, $startDate, $startTime, $endDate, $endTime, $numberOfPlaces, $location, $isSubscriptionValidationRequired);

			$result = $session->Save($event);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("Event $title added");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Attach a poster on an event
	*
	* @param int $idEvent The event id
	* @param binary[] $file The poster file
	* 
	* @return ServiceResponse This response contains the event with his poster
	*/
	public function attachPosterOnAnEvent($idEvent, $file, $mime, $extension)
	{
		Core\CoreCommons\Logger::Info("attachPosterOnAnEvent $idEvent, $mime, $extension");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$event = $session->Load('Event', $idEvent);
			
			$file = mysql_real_escape_string($file);
			
			$event->Picture = $file;
			$event->PictureMime = $mime;
			$event->PictureExtension = $extension;
			$event->ModificationDate = date("Y-m-d H:i:s");
			
			$result = $session->Update($event);
			
			//$result = $session->Delete($event);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("Event $idEvent has a new poster");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/** 
	* Pre subscribe an user to an event
	*
	* @param integer $userId The user who want to subscribe
	* @param integer $eventId The user event's want to participate
	*
	* @return ServiceResponse This response contains event subscription
	*/
	public function preSubscribe($userId, $eventId)
	{
		Core\CoreCommons\Logger::Info("Service - preSubscribe $userId, $eventId");
		
		$response = null;
		
		try
		{	
			//check if user has already subscribe on this event
			$alreadySubscribeResult = $this->getSubscriptionsFromUserOnEvent($userId, $eventId);

			if(count($alreadySubscribeResult->response) > 0)
			{
				throw new \Exception("Vous avez déjà fait une demande d'inscription pour cet événement.");
			}
		
			$session = Core\Datastorage\Session::Instance();
			$session->Open();

			$user = $session->Load('User', $userId);
			$event = $session->Load('Event', $eventId);

			$eventSubscription = Core\CoreContracts\EventSubscription::Create($event, $user);
			
			//Automatic validation for subscription validation not required
			if($event->IsSubscriptionValidationRequired == false)
			{
				$eventSubscription->Valid();
			}
			
			$eventSubscription->Event = $eventId;
			$eventSubscription->User = $userId;
			
			$result = $session->Save($eventSubscription);
			
			$eventSubscription->Event = $event;
			$eventSubscription->User = $user;
			
			//Manage mail to inform the user
			$values = array();
			$mail = null;
			switch ($eventSubscription->State) 
			{
				case 0:
					$values['#firstname'] = $user->Firstname;
					$values['#lastname'] = $user->Lastname;
					$values['#eventtitle'] = $event->Title;
					$values['#eventdate'] = $event->StartDate;
					$mail = new Core\CoreCommons\Mail("EventSubscriptionPlan", $values);
					break;
				case 3:
					$values['#firstname'] = $user->Firstname;
					$values['#lastname'] = $user->Lastname;
					$values['#eventtitle'] = $event->Title;
					$values['#eventdate'] = $event->StartDate;
					$mail = new Core\CoreCommons\Mail("EventSubscriptionValid", $values);
					break;
			}

			//$mail->Send($user->Email);
			
			$response = new Core\CoreCommons\ServiceResponse($eventSubscription);

			$session->Close();
			
			Core\CoreCommons\Logger::Info("Service - preSubscribe completed");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/** 
	* Get all get all event subscriptions
	*
	* @return ServiceResponse This response contains all event subscription
	*/
	public function getEventSubscriptions()
	{
		Core\CoreCommons\Logger::Info("Start to get all event subscriptions");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();

			$session->CreateCriteria('EventSubscription');
			$result = $session->ListResult();

			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			
			Core\CoreCommons\Logger::Info("Get all event subscriptions completed");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/** 
	* Get all personal events
	*
	* @return ServiceResponse This response contains all personal events
	*/
	public function getPersonalEvents($userId)
	{	
		Core\CoreCommons\Logger::Info("Start to get all personal");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();

			$session->CreateCriteria('EventSubscription');
			$session->AddCriteria( Core\Datastorage\Expression::SQL_EQ('User', $userId));
			$result = $session->ListResult();
			
			$validEventSubscriptions = array(); 
			
			foreach($result as $eventSubscription)
			{
				if($eventSubscription->State == Core\CoreContracts\StateEventSubscription::Planned ||
				$eventSubscription->State == Core\CoreContracts\StateEventSubscription::Paid ||
				$eventSubscription->State == Core\CoreContracts\StateEventSubscription::Valid)
				{
					array_push($validEventSubscriptions, $eventSubscription);
				}
			}
			
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			
			Core\CoreCommons\Logger::Info("Get all personal events completed");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/** 
	* Set user as partner on an event subscription
	*
	* @param 
	*
	* @return ServiceResponse This response contains event subscription
	*/
	public function userIsPartner($eventSubscriptionId, $isPartner)
	{
		Core\CoreCommons\Logger::Info("Start set user is partner, event subscription Id : $eventSubscriptionId / is a partner : $isPartner");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$eventSubscription = $session->Load('EventSubscription', $eventSubscriptionId);
			$eventSubscription->IsPartner = $isPartner;
			$eventSubscription->ModificationDate = date("Y-m-d H:i:s");
			
			$fieldsToUpdate = array('IsPartner' => $eventSubscription->IsPartner, 'ModificationDate' => $eventSubscription->ModificationDate);
			
			$result = $session->Update($eventSubscription, $fieldsToUpdate);
			$response = new Core\CoreCommons\ServiceResponse($result);
			
			$session->Close();
			
			Core\CoreCommons\Logger::Info("Set user is partner is completed");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get all participants on an event
	* 
	* @param integer $id The event id
	*
	* @return ServiceResponse This response contains all participants
	*/
    public function getParticipants($id)
	{
		Core\CoreCommons\Logger::Info("Start to get all participants from $id");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();

			$session->CreateCriteria('EventSubscription');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('Event', $id));
			$result = $session->ListResult();
			
			$participants = array();
			
			foreach($result as $eventSubscription)
			{
				array_push($participants, $eventSubscription);
			}
			
			$response = new Core\CoreCommons\ServiceResponse($participants);

			$session->Close();
			
			Core\CoreCommons\Logger::Info("Get all participants completed");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/** 
	* Get all event subscriptions to valid
	*
	* @return ServiceResponse This response contains all event subscription to valid
	*/
	public function getEventSubscriptionsToValid()
	{	
		Core\CoreCommons\Logger::Info("Start to get all event subscriptions to valid");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();

			$session->CreateCriteria('EventSubscription');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('State', Core\CoreContracts\StateEventSubscription::Planned));
			$result = $session->ListResult();

			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			
			Core\CoreCommons\Logger::Info("Get all event subscriptions to valid completed");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get all event subscriptions states
	*
	* @return ServiceResponse This response contains all states event subscriptions
	*/
	public function getEventSubscriptionStates()
	{
		Core\CoreCommons\Logger::Info("getEventSubscriptionStates");
		
		$response = null;
		
		try
		{	
			$eventSubscriptionStates = new Core\CoreContracts\StateEventSubscription();
			
			$response = new Core\CoreCommons\ServiceResponse($eventSubscriptionStates->getArray());

			Core\CoreCommons\Logger::Info("Get all event subscription states is finished");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/** 
	* Update the event subscription event subscriptions
	*
	* @param integer $id The event subscription id
	* @param integer $state The event subscription new state
	*
	* @return ServiceResponse This response contains all event subscription
	*/
	public function updateEventSubscription($id, $state)
	{
		Core\CoreCommons\Logger::Info("updateEventSubscription $id, $state");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$eventSubscription = $session->Load('EventSubscription', $id);
			
			switch ($state) 
			{
				case 0:
					$eventSubscription->Plan();
					break;
				case 1:
					$eventSubscription->Pay();
					break;
				case 2:
					$eventSubscription->Cancel();
					break;
				case 3:
					$eventSubscription->Valid();
					break;
			}

			$result = $session->Update($eventSubscription);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("updateEventSubscription $id was updated");
			
			Core\CoreCommons\Logger::Info(sprintf("Send a mail to the user %s in order to inform him.", $eventSubscription->User->Id));
			
			$values = array();
			$mail = null;
			switch ($state) 
			{
				case 0:
					$eventSubscription->Plan();
					$values['#firstname'] = $eventSubscription->User->Firstname;
					$values['#lastname'] = $eventSubscription->User->Lastname;
					$values['#eventtitle'] = $eventSubscription->Event->Title;
					$values['#eventdate'] = $eventSubscription->Event->StartDate;
					$mail = new Core\CoreCommons\Mail("EventSubscriptionPlan", $values);
					break;
				case 1:
					$eventSubscription->Pay();
					$values['#firstname'] = $eventSubscription->User->Firstname;
					$values['#lastname'] = $eventSubscription->User->Lastname;
					$values['#eventtitle'] = $eventSubscription->Event->Title;
					$values['#eventdate'] = $eventSubscription->Event->StartDate;
					$mail = new Core\CoreCommons\Mail("EventSubscriptionPay", $values);
					break;
				case 2:
					$eventSubscription->Cancel();
					$values['#firstname'] = $eventSubscription->User->Firstname;
					$values['#lastname'] = $eventSubscription->User->Lastname;
					$values['#eventtitle'] = $eventSubscription->Event->Title;
					$values['#eventdate'] = $eventSubscription->Event->StartDate;
					$mail = new Core\CoreCommons\Mail("EventSubscriptionCancel", $values);
					break;
				case 3:
					$eventSubscription->Valid();
					$values['#firstname'] = $eventSubscription->User->Firstname;
					$values['#lastname'] = $eventSubscription->User->Lastname;
					$values['#eventtitle'] = $eventSubscription->Event->Title;
					$values['#eventdate'] = $eventSubscription->Event->StartDate;
					$mail = new Core\CoreCommons\Mail("EventSubscriptionValid", $values);
					break;
			}

			$mail->Send($eventSubscription->User->Email);
		}
		catch (\Exception $ex) 
		{
			Core\CoreCommons\Logger::Error("updateEventSubscription " . serialize($ex));
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/** 
	* Get all subscription from the user
	*
	* @param integer $userId The user who want to subscribe
	* @param integer $eventId The user event's want to participate
	*
	* @return ServiceResponse This response contains event subscription
	*/
	public function getSubscriptionsFromUserOnEvent($userId, $eventId)
	{
		Core\CoreCommons\Logger::Info("Service - getSubscriptionsFromUserOnEvent $userId, $eventId");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();

			$session->CreateCriteria('EventSubscription');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('User', $userId));
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('Event', $eventId));
			$result = $session->ListResult();
			
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			
			Core\CoreCommons\Logger::Info("Service - getSubscriptionsFromUserOnEvent completed");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get all events
	* 
	* @return ServiceResponse This response contains all events
	*/
    public function getEvents()
	{
		Core\CoreCommons\Logger::Info("Service - getEvents");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
		
			$session->CreateCriteria('Event');
			$result = $session->ListResult();
			
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			
			Core\CoreCommons\Logger::Info("Service - getEvents completed");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get all event states
	*
	* @return ServiceResponse This response contains all states event
	*/
	public function getStates()
	{
		Core\CoreCommons\Logger::Info("getStates");
		
		$response = null;
		
		try
		{	
			$eventStates = new Core\CoreContracts\StateEvent();
			
			$response = new Core\CoreCommons\ServiceResponse($eventStates->getArray());

			Core\CoreCommons\Logger::Info("Get all states is finished");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get all archives event
	*
	* @param integer $id The event id
	*
	* @return ServiceResponse This response contains all archives event
	*/
	public function getArchivesEvent($archiveRootPath, $id)
	{
		Core\CoreCommons\Logger::Info("Start to get all archives event from event $id ");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$event = $session->Load('Event', $id);
			
			if(isset($event) == false)
			{
				throw new \Exception("L'événement $id est introuvable");
			}
			
			$documentServices = new Core\CoreComponents\DocumentsManager\Documents();
			
			$documents = $documentServices->getDocuments($archiveRootPath . DIRECTORY_SEPARATOR . $event->ArchiveName, true, null);
		
			//Build all url
			$parameters = Core\CoreCommons\Parameters::Singleton();
			$urlBase = $parameters::$Keys["UrlBase"];
			$paths = array();
			
			foreach($documents->response as $document)
			{
				$path = sprintf("%sArchives/%s/%s", $urlBase, $event->ArchiveName, $document->Name);
				array_push($paths, $path);
			}
			
			$response = new Core\CoreCommons\ServiceResponse($paths);
			
			$session->Close();
			
			Core\CoreCommons\Logger::Info("Get all archives event is completed");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get all online events
	* 
	* @return ServiceResponse This response contains all online events
	*/
    public function getOnlineEvents()
	{
		Core\CoreCommons\Logger::Info("Service - getOnlineEvents");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
		
			$session->CreateCriteria('Event');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('State', Core\CoreContracts\StateEvent::Planned));
			//$session->OrderBy('StartDate', 'asc');
			$result = $session->ListResult();
			
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			
			Core\CoreCommons\Logger::Info("Service - getOnlineEvents completed");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/** 
	* Get all valid event subscriptions for planned events
	*
	* @return ServiceResponse This response contains all valid event subscription for planned events
	*/
	public function getValidEventSubscriptionsForPlannedEvent()
	{
		Core\CoreCommons\Logger::Info("Service - getValidEventSubscriptionsForPlannedEvent");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
		
			$session->CreateCriteria('EventSubscription');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('State', Core\CoreContracts\StateEventSubscription::Valid));
			$result = $session->ListResult();
			
			$plannedEvent = array();
			
			foreach($result as $eventSubscription)
			{
				if($eventSubscription->Event->State == Core\CoreContracts\StateEvent::Planned)
				{
					array_push($plannedEvent, $eventSubscription);
				}
			}
			
			$response = new Core\CoreCommons\ServiceResponse($plannedEvent);

			$session->Close();
			
			Core\CoreCommons\Logger::Info("Service - getValidEventSubscriptionsForPlannedEvent completed");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get all done events
	* 
	* @return ServiceResponse This response contains all done events
	*/
    public function getDoneEvents()
	{
		Core\CoreCommons\Logger::Info("Service - getDoneEvents");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
		
			$session->CreateCriteria('Event');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('State', Core\CoreContracts\StateEvent::Done));
			$result = $session->ListResult();
			
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			
			Core\CoreCommons\Logger::Info("Service - getDoneEvents completed");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Delete an event
	* 
	* @param integer $id The unique event identifier
	*
	* @return ServiceResponse This response contains the deleted event
	*/
	public function deleteEvent($id)
	{
		Core\CoreCommons\Logger::Info("deleteEvent $id");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$event = $session->Load('Event', $id);

			$result = $session->Delete($event);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("Event $id deleted");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Update an event
	* 
	* @param integer $id The unique event identifier
	* @param string $title The event title
	* @param string $description The event description
	* @param datetime $eventDate The event date
	* @param int $numberOfPlaces The number of places
	* @param string $archiveName The archive name
	* @param int $state The event state
	* @param string $location The event location
	*
	* @return ServiceResponse This response contains the updated event
	*/
	public function updateEvent($id, $title, $description, $startDate, $startTime, $endDate, $endTime, $numberOfPlaces, $archiveName, $state, $location)
	{
		Core\CoreCommons\Logger::Info("updateEvent $id, $title, $description, $startDate, $startTime, $endDate, $endTime, $numberOfPlaces, $archiveName, $state, $location");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$event = $session->Load('Event', $id);
			$event->Title = $title;
			$event->Description = $description;
			$event->NumberOfPlaces = $numberOfPlaces;
			$event->StartDate = $startDate;
			$event->StartTime = $startTime;
			$event->EndDate = $endDate;
			$event->EndTime = $endTime;
			$event->ArchiveName = $archiveName;
			$event->Location = $location;
			
			switch ($state) 
			{
				case 0:
					$event->Edit();
					break;
				case 1:
					$event->Edit();
					break;
				case 2:
					$event->Plan();
					break;
				case 3:
					$event->CloseSubscriptions();
					break;
				case 4:
					$event->Run();
					break;
				case 5:
					$event->Cancel();
					break;
				case 6:
					$event->Done();
					break;
			}
			
			$fieldsToUpdate = array('Title' => $event->Title, 'Description' => $event->Description, 'NumberOfPlaces' => $event->NumberOfPlaces, 'StartDate' => $event->StartDate, 'StartTime' => $event->StartTime, 'EndDate' => $event->EndDate, 'EndTime' => $event->EndTime, 'ArchiveName' => $event->ArchiveName, 'Location' => $event->Location, 'State' => $event->State, 'ModificationDate' => $event->ModificationDate);

			$result = $session->Update($event, $fieldsToUpdate);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("Event $id updated");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Attach an archive to an event
	* 
	* @param integer $id The unique event identifier
	* @param string $archiveName The archive folder name
	*
	* @return ServiceResponse This response contains the deleted event
	*/
	public function attachArchive($idEvent, $archiveName)
	{
		Core\CoreCommons\Logger::Info("attachArchive $idEvent, $archiveName");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$event = $session->Load('Event', $idEvent);
			
			$event->ArchiveName = $archiveName;
			$event->ModificationDate = date("Y-m-d H:i:s");
			
			$result = $session->Update($event);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("Event $idEvent updated");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Plan an event
	* 
	* @param integer $id The unique event identifier
	*
	* @return ServiceResponse This response contains the planned event
	*/
	public function planEvent($id)
	{
		Core\CoreCommons\Logger::Info("planEvent $id");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$event = $session->Load('Event', $id);
			$event->Plan();
			
			$result = $session->Update($event);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("Event $id planned");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Close subscriptions on an event
	* 
	* @param integer $id The unique event identifier
	*
	* @return ServiceResponse This response contains the closed subscriptions event
	*/
	public function closeSubscriptionsEvent($id)
	{
		Core\CoreCommons\Logger::Info("closeSubscriptions $id");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$event = $session->Load('Event', $id);
			$event->CloseSubscriptions();
			
			$result = $session->Update($event);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("Event $id subscriptions closed");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Run an event
	* 
	* @param integer $id The unique event identifier
	*
	* @return ServiceResponse This response contains the running event
	*/
	public function runEvent($id)
	{
		Core\CoreCommons\Logger::Info("runEvent $id");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$event = $session->Load('Event', $id);
			$event->Run();
			
			$result = $session->Update($event);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("Event $id runt");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Cancel an event
	* 
	* @param integer $id The unique event identifier
	*
	* @return ServiceResponse This response contains the cancelled event
	*/
	public function cancelEvent($id)
	{
		Core\CoreCommons\Logger::Info("cancelEvent $id");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$event = $session->Load('Event', $id);
			$event->Cancel();
			
			$result = $session->Update($event);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("Event $id cancelled");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Done an event
	* 
	* @param integer $id The unique event identifier
	*
	* @return ServiceResponse This response contains the done event
	*/
	public function doneEvent($id)
	{
		Core\CoreCommons\Logger::Info("doneEvent $id");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$event = $session->Load('Event', $id);
			$event->Done();
			
			$result = $session->Update($event);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("Event $id is done");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Attach an attachment on an event
	* 
	* @param integer $eventId The unique event identifier
	* @param binary[] $file The file content
	* @param string $mime The mime file
	* @param string $extension The extension file
	*
	* @return ServiceResponse This response contains the event attachment
	*/
	public function attachEventAttachment($eventId, $name, $file, $mime, $extension)
	{
		Core\CoreCommons\Logger::Info("attachEventAttachment $eventId");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$file = mysql_real_escape_string($file);
				
			$event = $session->Load('Event', $eventId);
			
			//Check if event exist
			if(isset($event) == false)
			{
				throw new \Exception("L'événement $eventId est introuvable");
			}
				
			$eventAttachment = Core\CoreContracts\EventAttachment::Create($eventId, $name, $file, $mime, $extension);
			
			$result = $session->Save($eventAttachment);
			
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("attachEventAttachment $eventId is done");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get all event attachments
	* 
	* @param integer $eventId The unique event identifier
	*
	* @return ServiceResponse This response contains all event attachments
	*/
	public function getEventAttachments($eventId)
	{
		Core\CoreCommons\Logger::Info("getEventAttachments $eventId");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();

			$session->CreateCriteria('EventAttachment');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('Event', $eventId));
			$result = $session->ListResult();
			
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("getEventAttachments $eventId is done");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get all event attachments
	* 
	* @param integer $eventId The unique event identifier
	*
	* @return ServiceResponse This response contains all event attachments
	*/
	public function getEventAttachment($id)
	{
		Core\CoreCommons\Logger::Info("getEventAttachment $id");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();

			$result = $session->Load('EventAttachment', $id);
			
			if(isset($result) == false)
			{
				throw new \Exception("La pièce jointe $id n'existe pas");
			}
			
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			
			Core\CoreCommons\Logger::Info("getEventAttachment $id is done");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Delete an event attachment
	* 
	* @param integer $eventId The unique event identifier
	*
	* @return ServiceResponse This response contains all event attachments
	*/
	public function deleteEventAttachment($id)
	{
		Core\CoreCommons\Logger::Info("deleteEventAttachment $id");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$eventAttachment = $session->Load('EventAttachment', $id);
			
			if(isset($eventAttachment) == false)
			{
				throw new \Exception("La pièce jointe $id n'existe pas");
			}

			$result = $session->Delete($eventAttachment);

			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			
			Core\CoreCommons\Logger::Info("deleteEventAttachment $id is done");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
}

?> 